<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <!-- 头部按钮 -->
        <template #header>
            <el-button type="primary" size="default" :icon="CirclePlusFilled" @click="addTrademark">添加</el-button>
        </template>
        <!-- 表格 -->
        <el-table :data="tableData" border stripe :style="{marginBottom: '20px'}">
            <el-table-column type="index" width="120" label="序号" align="center"/>
            <el-table-column label="品牌名称" prop="tmName" />
            <el-table-column label="品牌LOGO">
                <template v-slot="{row}">
                    <img :src="row.logoUrl" height="80"/>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="220" align="center">
                <template v-slot="{row}">
                    <el-button type="warning" size="default" :icon="Edit" @click="updateTrademark(row)">修改</el-button>
                    <el-button type="danger" size="default" :icon="Delete" @click="deleteTrademark(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 页码 -->
        <el-pagination
            v-model:current-page="page"
            v-model:page-size="limit"
            :total="total"
            :page-sizes="[3, 5, 7, 10]"
            :pager-count="7"
            layout="prev, pager, next , sizes ,  total"
        ></el-pagination>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="添加或者修改">
        <el-form label-width="100px" :model="newTrademark" :rules="rules" ref="fromEle">
            <el-form-item label="品牌名称" prop="tmName">
                <el-input  autocomplete="off" v-model="newTrademark.tmName"/>
            </el-form-item>
            <el-form-item label="品牌LOGO" prop="logoUrl">
                <el-upload
                    class="avatar-uploader"
                    :action="`${baseUrl}/admin/product/fileUpload`"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                >
                    <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submitTrademark">确认</el-button>
        </template>
    </el-dialog>
    
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";

export default defineComponent({
    name: "Trademark",
});
</script>
<script setup lang="ts">
import {CirclePlusFilled , Edit , Delete , Plus} from "@element-plus/icons-vue"
import {ref , toRefs , onMounted , watch , reactive , markRaw} from "vue"
import {
    requestGetGoodsList,
    requestAddGoods,
    requestUpdateGoods,
    requestDeleteGoods,
} from "@/api/trademark"
import type {reqGoodsRecodesType , reqGoodsValue} from "@/api/trademark"
import { type UploadProps , type FormRules , type FormInstance, ElMessageBox} from 'element-plus'

//1.表格逻辑
//定义表格数据
const tableData = ref<reqGoodsRecodesType>([])

//2.页码逻辑
const pageData = ref({
    page: 1,
    limit: 3,
    total: 100
})
const {page , limit , total} = toRefs(pageData.value)


//3.商品分页列表逻辑
//封装请求商品分页列表函数
const getGoodsList = async () => {
    try {
        //发送请求
        const result = await requestGetGoodsList(page.value , limit.value)
        //把请求回来的商品数据给表格数据
        tableData.value = result.records
        //把总页数据给分页器
        total.value = result.total
    } catch (error) {
        //请求失败提示
        ElMessage.error("请求商品列表出现异常...")
    }
}
//初始化请求商品分页列表
onMounted(() => {
    getGoodsList()  
});
//监听页码改变重新发送请求获取分页列表
watch([page , limit] , () => {
    getGoodsList()
})


//4.弹窗逻辑
//定义数据控制弹窗显示隐藏
const dialogFormVisible = ref(false)
//保存前缀
const baseUrl = import.meta.env.VITE_API_URL
//定义数据保存一个新的商品
const newTrademark = ref({
    id: 0,
    logoUrl: "",
    tmName: "",
})
//上传图片成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
    //把上传成功响应的图片保存的我们的数据，等下添加要用
    newTrademark.value.logoUrl = response.data
    //上传成功把图片校验的错误信息清空
    fromEle.value?.clearValidate("logoUrl")
}
//上传图片之前的回调
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}


//5.点击添加的回调
const addTrademark = () => {
    //点击添加把之前的表单校验信息清空
    fromEle.value?.clearValidate()
    //显示弹窗
    dialogFormVisible.value = true
    //清空弹窗数据
    newTrademark.value = {
        id: 0,
        logoUrl: "",
        tmName: "",
    }
}

//6.点击修改的回调
const updateTrademark = (row: reqGoodsValue) => {
    //点击修改之前清空之前的表单校验错误信息
    fromEle.value?.clearValidate()
    //显示弹窗
    dialogFormVisible.value = true
    //数据回填
    newTrademark.value = {...row}
}

//8.点击确认的回调
const submitTrademark = () => {
    //点击确定先进行表单校验
    fromEle.value?.validate()
    //校验成功进入then去执行添加或修改逻辑
    .then(async ()=>{
        //开始尝试发送添加或者修改请求
        try {
            //判断是修改还是添加
            if(!newTrademark.value.id){
                //发送新增请求
                await requestAddGoods(newTrademark.value)
                //添加成功回到第一页
                page.value = 1
                //重新请求分页列表
                getGoodsList()
                //提示
                ElMessage.success("添加成功")
            }else{
                //发送修改请求
                await requestUpdateGoods(newTrademark.value)
                //重新请求分页列表
                getGoodsList()
                //提示
                ElMessage.success("修改成功")
            } 
            //添加成功或者修改成功都关闭弹窗
            dialogFormVisible.value = false
        } catch (error) {
            //失败提示
            newTrademark.value.id? ElMessage.error("修改失败") : ElMessage.error("添加失败")
        }
    })
    //校验失败进入catch,并提示用户
    .catch(()=>{
        ElMessage.error("表单校验失败")
    })  
}
//点击取消的回调
const cancel = () => {
    //关闭弹窗
    dialogFormVisible.value = false
    //提示
    ElMessage.success("取消操作")
}


//获取表单实例
const fromEle = ref<FormInstance>()
//自定义表单校验规则
const mayRules = (rule: any, value: string, callback: any) => {
    //判断输入的内容长度在2-6位之间
    if(value.length < 2 || value.length > 6){
        callback("输入的内容长度不合法")
    }else{
        callback()
    }
}
//定义表单校验的规则
const rules = reactive<FormRules>({
    tmName: [
        {required: true, message: "输入内容不能为空", trigger: "blur"},
        {validator: mayRules , trigger: "blur"}
    ],
    logoUrl: [{required: true , message: "必须上传图片"}]
})

//9.点击删除的回调函数
const deleteTrademark  = (id: number) => {
    //点击删除之前先弹出消息提示框，根据用户点击决定是执行删除操作还是取消
    ElMessageBox.confirm("真的要删除吗",  "警告!" , {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
        icon: markRaw(Delete),
    })
    .then(async ()=>{
        try {
            //用户点击确定后执行删除操作
            await requestDeleteGoods(id)
            //删除成功提示
            ElMessage.success("删除成功!")
            //重新请求分页列表
            getGoodsList()
        } catch (error) {
            error;
        }
    })
    //点击取消删除进入catch
    .catch(()=>{
        ElMessage.success("取消删除!")
    })

}


</script>

<style scoped>
    .avatar-uploader .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
</style>   
<style>
    .avatar-uploader .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    
    .avatar-uploader .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
</style>